package logic

import (
	"errors"
	"fmt"
	"mime/multipart"
	"os"
	"strconv"
	"strings"
	"whale/internal/app/admin/consts/res"
	"whale/internal/app/admin/model"
	"whale/internal/repository"
	"whale/pkg/file"
	"whale/pkg/utils"

	"github.com/gofiber/fiber/v2"
)

// generate logic *UploadLogic  IUploadLogic
type IUploadLogic interface {
	// 图片上传
	UploadImage(ctx *fiber.Ctx) (interface{}, error)
}

// 图片上传
func (logic *UploadLogic) UploadImage(ctx *fiber.Ctx) (interface{}, error) {
	var (
		fileVal  *multipart.FileHeader
		fileMime string
		fileSize int64
		err      error
	)
	fileVal, err = ctx.FormFile("file")
	if err != nil {
		return nil, errors.New("图片获取失败")
	}
	// 验证图片大小
	fileSize, err = strconv.ParseInt(os.Getenv("IMAGE_SIZE"), 10, 64)
	if err != nil {
		return nil, fmt.Errorf("字节转换失败:%s", err.Error())
	}
	if fileVal.Size > (int64(fileSize) * 1024 * 1024) {
		return nil, fmt.Errorf("图片的大小超出约束")
	}
	// 验证图片格式
	fileMime, err = file.GetFileType(fileVal)
	if err != nil {
		return nil, errors.New("文件类型不合法")
	}

	// 开始上传处理
	var fileData = &model.File{
		Type: "admin",
		Hash: utils.HashMd5(fileVal.Filename),
		Name: fileVal.Filename,
		Xext: strings.Split(fileVal.Filename, ".")[1],
		Mime: fileMime,
		Size: int(fileVal.Size),
		Xkey: os.Getenv("UPLOAD_FILE_PATH"),
	}

	if err := file.MkdirExist(fileData.Xkey); err != nil {
		return nil, fmt.Errorf("文件目录检测异常%s", err.Error())
	}
	// TODO 开启事务

	// 上传成功并且数据提交成功
	filePath := "/image/" + fileData.Hash + "." + fileData.Xext
	fileData.Xurl = os.Getenv("FILE_HOST") + filePath

	savePath := fileData.Xkey + filePath
	fileData.Xkey = savePath

	if err := ctx.SaveFile(fileVal, savePath); err != nil {
		return nil, fmt.Errorf("文件上传失败%s", err.Error())
	}
	// 提交
	logic.Repository.Table(&model.File{}).Insert(&fileData)
	return &res.UploadImageRes{
		ImageSrc: fileData.Xurl,
	}, nil
}

type UploadLogic struct {
	Repository repository.IRepository `bean:"Repository"`
}
